package com.gcloud.mesh.dcs.rpc;

import com.gcloud.mesh.grpc.api.*;
import com.gcloud.mesh.header.msg.agent.SetDvfsMsg;
import com.gcloud.mesh.header.msg.agent.SetDvfsReplyMsg;
import com.gcloud.mesh.header.msg.dvfs.SyncDvfsReplyMsg;
import io.grpc.ManagedChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RPCClient {

    @Autowired
    private RPCConfig rpcConfig;

    public SetDvfsReplyMsg setDvfs(SetDvfsMsg msg, String ip) {
        ManagedChannel managedChannel = rpcConfig.getManagedChannel(ip);
        if (managedChannel != null) {
            try {
                RPCSetDvfsServiceGrpc.RPCSetDvfsServiceBlockingStub setDvfsService = RPCSetDvfsServiceGrpc.newBlockingStub(managedChannel);
                log.info("[RPCClient->setDvfs] set dvfs发送的信息为：{}", msg);
                RPCSetDvfsRequest setDvfsRequest = RPCSetDvfsRequest
                        .newBuilder()
                        .setNodeId(msg.getNodeId())
                        .setStrategy(msg.getStrategy())
                        .setFrequency(msg.getFrequency())
                        .build();
                RPCSetDvfsResponse setDvfsResponse = setDvfsService.setDvfs(setDvfsRequest);
//            log.info("[RPCSetDvfsClient]set dvfs响应信息为：{}",setDvfsResponse.getSuccess());
            } finally {
                managedChannel.shutdown();
            }
        }
        return null;
    }

    public SyncDvfsReplyMsg syncDvfs(String ip) {
        ManagedChannel managedChannel = rpcConfig.getManagedChannel(ip);
        if (managedChannel != null) {
            try {
                RPCSyncDvfsServiceGrpc.RPCSyncDvfsServiceBlockingStub syncDvfsService = RPCSyncDvfsServiceGrpc.newBlockingStub(managedChannel);
                log.info("[RPCClient->syncDvfs] sync dvfs发送请求");
                RPCSyncDvfsRequest syncDvfsRequest = RPCSyncDvfsRequest
                        .newBuilder()
                        .build();
                RPCSyncDvfsResponse syncDvfsResponse = syncDvfsService.syncDvfs(syncDvfsRequest);
            } finally {
                managedChannel.shutdown();
            }
        }
        return null;
    }
}
